package com.ytrsoft.utils;

import com.ytrsoft.bean.IOType;
import com.ytrsoft.bean.Message;
import com.ytrsoft.io.ProcessOutputStream;
import com.ytrsoft.io.ProcessOutputStreamListener;
import com.ytrsoft.io.StreamRedirector;
import com.ytrsoft.ws.BaseSocket;

import java.io.IOException;

public class ProcessManager extends Thread implements ProcessOutputStreamListener {

    private Process process;
    private final BaseSocket socket;
    private ProcessOutputStream stdout;
    private ProcessOutputStream stderr;

    public ProcessManager(BaseSocket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        String[] cmd = Commands.get();
        ProcessBuilder pb = new ProcessBuilder(cmd);
        try {
            process = pb.start();
            stdout = new ProcessOutputStream(System.out);
            stdout.setOnProcessOutputStreamListener(this);
            stderr = new ProcessOutputStream(System.err);
            stderr.setOnProcessOutputStreamListener(this);
            new StreamRedirector(process.getInputStream(), stdout).start();
            new StreamRedirector(process.getErrorStream(), stderr).start();
            process.waitFor();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    public Process getProcess() {
        return process;
    }

    public void close() {
        if (process != null && !process.isAlive()) {
            process.destroy();
        }
        if (stderr != null) {
            stderr.close();
        }
        if (stdout != null) {
            stdout.close();
        }
    }

    @Override
    public void out(IOType type, String body) {
        Message msg = MsgKit.create(type, body);
        socket.postMessage(msg);
    }
}
